package org.example.DAO;
import org.example.entity.Content;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static java.rmi.server.LogStream.log;

public class ContentDAO {
    private Content extractContentFromResultSet(ResultSet rs) throws SQLException {
        Content content = new Content();
        content.setId(rs.getString("id"));
        content.setTitle(rs.getString("title"));
        content.setType(rs.getString("type"));
        content.setDescription(rs.getString("description"));
        content.setStatus(rs.getString("status"));
        content.setCoverUrl(rs.getString("cover_url"));
        // 类型特定字段
        content.setDirector(rs.getString("director"));
        content.setActors(rs.getString("actors"));
        content.setAuthor(rs.getString("author"));
        content.setPublisher(rs.getString("publisher"));
        content.setArtist(rs.getString("artist"));
        content.setAlbum(rs.getString("album"));
        return content;
    }
    // 添加内容
    public String addContent(Content content) throws SQLException {
        String sql = "INSERT INTO content (id, title, type, cover_url, description, status, " +
                "director, actors, author, publisher, artist, album) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        String id = UUID.randomUUID().toString();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, id);
            pstmt.setString(2, content.getTitle());
            pstmt.setString(3, content.getType());
            pstmt.setString(4, content.getCoverUrl());
            pstmt.setString(5, content.getDescription());
            pstmt.setString(6, content.getStatus());
            // 设置类型特定字段
            if ("movie".equals(content.getType())) {
                pstmt.setString(7, content.getDirector());
                pstmt.setString(8, content.getActors());
                pstmt.setNull(9, Types.VARCHAR);
                pstmt.setNull(10, Types.VARCHAR);
                pstmt.setNull(11, Types.VARCHAR);
                pstmt.setNull(12, Types.VARCHAR);
            } else if ("book".equals(content.getType())) {
                pstmt.setNull(7, Types.VARCHAR);
                pstmt.setNull(8, Types.VARCHAR);
                pstmt.setString(9, content.getAuthor());
                pstmt.setString(10, content.getPublisher());
                pstmt.setNull(11, Types.VARCHAR);
                pstmt.setNull(12, Types.VARCHAR);
            } else if ("music".equals(content.getType())) {
                pstmt.setNull(7, Types.VARCHAR);
                pstmt.setNull(8, Types.VARCHAR);
                pstmt.setNull(9, Types.VARCHAR);
                pstmt.setNull(10, Types.VARCHAR);
                pstmt.setString(11, content.getArtist());
                pstmt.setString(12, content.getAlbum());
            }
            pstmt.executeUpdate();
            return id;
        }
    }
    // 更新内容
    public void updateContent(Content content) throws SQLException {
        String sql = "UPDATE content SET title = ?, type = ?, cover_url = ?, description = ?, status = ?, " +
                "director = ?, actors = ?, author = ?, publisher = ?, artist = ?, album = ? " +
                "WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, content.getTitle());
            pstmt.setString(2, content.getType());
            pstmt.setString(3, content.getCoverUrl());
            pstmt.setString(4, content.getDescription());
            pstmt.setString(5, content.getStatus());
            // 设置类型特定字段
            if ("movie".equals(content.getType())) {
                pstmt.setString(6, content.getDirector());
                pstmt.setString(7, content.getActors());
                pstmt.setNull(8, Types.VARCHAR);
                pstmt.setNull(9, Types.VARCHAR);
                pstmt.setNull(10, Types.VARCHAR);
                pstmt.setNull(11, Types.VARCHAR);
            } else if ("book".equals(content.getType())) {
                pstmt.setNull(6, Types.VARCHAR);
                pstmt.setNull(7, Types.VARCHAR);
                pstmt.setString(8, content.getAuthor());
                pstmt.setString(9, content.getPublisher());
                pstmt.setNull(10, Types.VARCHAR);
                pstmt.setNull(11, Types.VARCHAR);
            } else if ("music".equals(content.getType())) {
                pstmt.setNull(6, Types.VARCHAR);
                pstmt.setNull(7, Types.VARCHAR);
                pstmt.setNull(8, Types.VARCHAR);
                pstmt.setNull(9, Types.VARCHAR);
                pstmt.setString(10, content.getArtist());
                pstmt.setString(11, content.getAlbum());
            }
            pstmt.setString(12, content.getId());
            pstmt.executeUpdate();
        }
    }
    // 删除内容
    public void deleteContent(String id) throws SQLException {
        String sql = "DELETE FROM content WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, id);
            pstmt.executeUpdate();
        }
    }
    // 根据ID获取内容
    public Content getContentById(String id) throws SQLException {
        String sql = "SELECT * FROM content WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, id);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return extractContentFromResultSet(rs);
                }
            }
        }
        return null;
    }
    public List<Content> getContentsByType(String type) throws SQLException {
        List<Content> contents = new ArrayList<>();
        // 使用实际存在的数据库列名
        String sql = "SELECT id, title, type, cover_url, description, status, " +
                "director, actors, author, publisher, artist, album " +
                "FROM content WHERE type = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, type);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    contents.add(extractContentFromResultSet(rs));
                }
            }
        }
        return contents;
    }


    // 分页查询内容
    public List<Content> getAllContents(int page, int pageSize, String type) throws SQLException {
        int offset = (page - 1) * pageSize;

        log("Fetching contents - Page: " + page + ", PageSize: " + pageSize +
                ", Offset: " + offset + ", Type: " + (type != null ? type : "All"));

        StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM content");
        List<Content> contents = new ArrayList<>();

        // 添加类型过滤
        if (type != null && !type.isEmpty()) {
            sqlBuilder.append(" WHERE type = ?");
        }
        sqlBuilder.append(" LIMIT ? OFFSET ?");

        String sql = sqlBuilder.toString();
        log("SQL: " + sql);

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            int paramIndex = 1;

            // 设置类型参数
            if (type != null && !type.isEmpty()) {
                pstmt.setString(paramIndex++, type);
                log("Param " + (paramIndex - 1) + ": Type = " + type);
            }

            // 设置分页参数
            pstmt.setInt(paramIndex++, pageSize);
            log("Param " + (paramIndex - 1) + ": PageSize = " + pageSize);

            pstmt.setInt(paramIndex, offset);
            log("Param " + paramIndex + ": Offset = " + offset);

            try (ResultSet rs = pstmt.executeQuery()) {
                int count = 0;
                while (rs.next()) {
                    count++;
                    contents.add(extractContentFromResultSet(rs));
                }
                log("Fetched " + count + " records");
            }

            return contents;
        } catch (SQLException e) {
            log("Error fetching contents: " + e.getMessage());
            throw e;
        }
    }

    // 计算内容总数
    public int getContentCount(String type) throws SQLException {
        String sql = "SELECT COUNT(*) FROM content";
        if (type != null && !type.isEmpty()) {
            sql += " WHERE type = ?";
        }
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            if (type != null && !type.isEmpty()) {
                pstmt.setString(1, type);
            }
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }
        }
        return 0;
    }
    // 更新内容状态
    public void updateContentStatus(String id, String status) throws SQLException {
        String sql = "UPDATE content SET status = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, status);
            pstmt.setString(2, id);
            pstmt.executeUpdate();
        }
    }
}